<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      ref="tenantTable"
      v-loading="listLoading"
      :data="tenantList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="租户名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租户编号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0">正常</el-tag>
          <el-tag v-else type="danger">冻结</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handlerDelete(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" style="text-align: right" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getTenants" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="center" label-width="80px">
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="租户编号" prop="code">
          <el-input-number v-model="temp.code" size="small" :min="1" ></el-input-number>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="temp.startTime"
            type="datetime"
            placeholder="选择开始日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="temp.endTime"
            type="datetime"
            placeholder="选择结束日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="endTime">
          <el-radio-group v-model="temp.status" size="small">
            <el-radio-button :label="0">正常</el-radio-button>
            <el-radio-button :label="1">冻结</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create'? createData() : updateData() ">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import { getTenantPage, addTenants, updateTenants, deleteTenants } from '@/api/tenant'
  export default {
    name: 'Tenant',
    components: { Pagination },
    data() {
      return {
        dialogStatus: '',
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '添加'
        },
        total: 0,
        listLoading: true,
        tenantList: [],
        listQuery: {
          current: 1,
          size: 10
        },
        temp: {
          id: undefined,
          name: '',
          code: 1,
          startTime: undefined,
          endTime: undefined,
          status: 0
        },
        rules: {
          name: [{ required: true, message: '请输入租户名称', trigger: 'blur' }],
          code: [{ required: true, message: '请输入租户编号', trigger: 'blur' }],
          startTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
          endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
          status: [{ required: true, message: '请选择租户状态', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.getTenants()
    },
    methods: {
      // 重置分页条件
      resetListQuery(size) {
        const pages = Math.ceil((this.total - size) / this.listQuery.size)
        const current = this.listQuery.current > pages ? pages : this.listQuery.current
        this.listQuery.current = current < 1 ? 1 : current
      },
      // 获取角色分页列表
      getTenants() {
        this.listLoading = true
        getTenantPage(this.listQuery).then(({ data }) => {
          this.tenantList = data.records
          this.total = data.total
          this.listLoading = false
        }).catch(error => {
          console.log(error)
          this.$message.error(error)
        })
      },
      // 重置表单
      resetTemp() {
        this.temp = {
          id: undefined,
          name: '',
          code: 1,
          startTime: undefined,
          endTime: undefined,
          status: 0
        }
      },
      // 获取多选的值
      handleSelectionChange(select) {
        this.batchIds = select
      },
      handlerDelete(id) {
        this.$confirm('您确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteTenants(id).then(() => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.resetListQuery(1)
            this.getTenants()
          }).catch(() => {
            this.$notify.error({
              title: '错误',
              message: '删除失败'
            })
          })
        })
      },
      // 弹出框
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 弹出框
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.startTime = this.$moment(this.temp.startTime).format('YYYY-MM-DD HH:mm:ss')
            this.temp.endTime = this.$moment(this.temp.startTime).format('YYYY-MM-DD HH:mm:ss')
            addTenants(this.temp).then(() => {
              this.getTenants()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            }).catch((error) => {
              this.$notify.error({
                title: '错误',
                message: '创建失败' + error
              })
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.startTime = this.$moment(this.temp.startTime).format('YYYY-MM-DD HH:mm:ss')
            this.temp.endTime = this.$moment(this.temp.endTime).format('YYYY-MM-DD HH:mm:ss')
            updateTenants(this.temp).then(() => {
              this.getTenants()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }).catch((error) => {
              this.$notify.error({
                title: '错误',
                message: '更新失败' + error
              })
            })
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
